<template>
  <a-layout>

    <a-layout-content
        :style="{background: '#fff', padding:'24px', margin: 0, minHeight:'280px'}">

      <a-row :gutter="16">

        <a-col :span="8">
          <a-form-item>
            <a-button type="primary" @click="add" >新增</a-button>
          </a-form-item>

          <a-table size="small" :row-key="record => record.id" :dataSource="level" :columns="columns" :pagination="false" @change="handleTableChange">
            <template #bodyCell="{ column, record }">

              <template v-if="column.key === 'action'">
                <a-space>
                  <a-button type="primary" shape="circle" @click="edit(record)">
                    <template #icon><edit-outlined /></template>
                  </a-button>

                  <a-popconfirm
                      title="是否确认删除?"
                      ok-text="是"
                      cancel-text="否"
                      @confirm="del(record.id)"
                  >
                    <a-button type="primary" danger shape="circle">
                      <template #icon><delete-outlined /></template>
                    </a-button>
                  </a-popconfirm>
                </a-space>
              </template>
            </template>
          </a-table>
        </a-col>

        <a-col :span="16">
<!--          表单-->
          <a-form :model="formState" :label-col="labelCol">

            <a-form-item>
              <a-button type="primary" @click="handleOk" >保存</a-button>
            </a-form-item>

            <a-form-item>
              <a-input v-model:value="formState.name" placeholder="文档名称" />
            </a-form-item>

            <a-form-item>
<!--              <a-select ref="select" v-model:value="formState.parent" placeholder="归类">-->
<!--                <a-select-option :key="0" :value="0">无</a-select-option>-->
<!--                <a-select-option v-for="c in level" :key="c.id" :value="c.id" :disabled="formState.id === c.id">{{ c.name }}</a-select-option>-->
<!--              </a-select>-->

              <a-tree-select
                  v-model:value="formState.parent"
                  show-search
                  style="width: 100%"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  placeholder="分类"
                  allow-clear
                  tree-default-expand-all
                  :tree-data="treeData"
                  :field-names="{
                    children: 'children',
                    label: 'name',
                    value: 'id',
                  }"
              >
              </a-tree-select>
            </a-form-item>

            <a-form-item>
              <a-input v-model:value="formState.sort" placeholder="序号" />
            </a-form-item>

            <a-form-item>
              <a-button type="primary" @click="showDrawer">内容预览</a-button>
            </a-form-item>

<!--            <a-form-item>-->
<!--              <a-input v-model:value="formState.viewCount" placeholder="阅读数" />-->
<!--            </a-form-item>-->

<!--            <a-form-item>-->
<!--              <a-input v-model:value="formState.voteCount" placeholder="点赞数" />-->
<!--            </a-form-item>-->

            <a-form-item>
              <Toolbar
                  style="border-bottom: 1px solid #ccc"
                  :editor="editorRef"
                  :defaultConfig="toolbarConfig"
                  :mode="mode"
              />
              <Editor
                  style="height: 500px; overflow-y: hidden;"
                  v-model="valueHtml"
                  :defaultConfig="editorConfig"
                  :mode="mode"
                  @onCreated="handleCreated"
              />
            </a-form-item>

          </a-form>

        </a-col>

      </a-row>

    </a-layout-content>

    <a-drawer
        v-model:visible="visible"
        class="custom-class"
        title="内容预览"
        placement="right"
        width="900px"
    >
      <div class="wangEditor" :innerHTML="valueHtml"></div>
    </a-drawer>

<!--    <a-modal v-model:visible="visible" title="Title" :confirm-loading="confirmLoading" @ok="handleOk">-->

<!--      &lt;!&ndash;      <p>表单</p>&ndash;&gt;-->
<!--      <a-form :model="formState" :label-col="labelCol" :wrapper-col="wrapperCol">-->

<!--        <a-form-item label="名称">-->
<!--          <a-input v-model:value="formState.name" />-->
<!--        </a-form-item>-->

<!--        <a-form-item label="父级分类">-->
<!--          <a-select ref="select" v-model:value="formState.parent">-->
<!--            <a-select-option :key="0" :value="0">无</a-select-option>-->
<!--            <a-select-option v-for="c in level" :key="c.id" :value="c.id" :disabled="formState.id === c.id">{{ c.name }}</a-select-option>-->
<!--          </a-select>-->
<!--        </a-form-item>-->

<!--        <a-form-item label="排序">-->
<!--          <a-input v-model:value="formState.sort" />-->
<!--        </a-form-item>-->

<!--        <a-form-item label="阅读数">-->
<!--          <a-input v-model:value="formState.viewCount" />-->
<!--        </a-form-item>-->

<!--        <a-form-item label="点赞数">-->
<!--          <a-input v-model:value="formState.voteCount" />-->
<!--        </a-form-item>-->

<!--        <a-form-item label="内容">-->
<!--          <Toolbar-->
<!--              style="border-bottom: 1px solid #ccc"-->
<!--              :editor="editorRef"-->
<!--              :defaultConfig="toolbarConfig"-->
<!--              :mode="mode"-->
<!--          />-->
<!--          <Editor-->
<!--              style="height: 500px; overflow-y: hidden;"-->
<!--              v-model="valueHtml"-->
<!--              :defaultConfig="editorConfig"-->
<!--              :mode="mode"-->
<!--              @onCreated="handleCreated"-->
<!--          />-->
<!--        </a-form-item>-->

<!--      </a-form>-->

<!--    </a-modal>-->
  </a-layout>
</template>

<script>
import {message} from "ant-design-vue"
import axios from "axios"
import {onMounted, ref, onBeforeUnmount, shallowRef} from "vue"
import {arrayToTree, isEmpty} from "@/util/Tool"
import {useRouter} from 'vue-router'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import {EditOutlined, DeleteOutlined} from "@ant-design/icons-vue"

export default {
  name: "AdminDoc",
  components: { Editor, Toolbar, EditOutlined, DeleteOutlined },
  setup() {

    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef()

    // 内容 HTML
    const valueHtml = ref('')

    const toolbarConfig = {}
    const editorConfig = { placeholder: '请输入内容...' }

    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = editorRef.value
      if (editor == null) return
      editor.destroy()
    })

    const handleCreated = (editor) => {
      editorRef.value = editor // 记录 editor 实例，重要！
    }

    const formState = ref({})
    const doc = ref()
    const columns = ref([
      {
        title: '名称',
        dataIndex: 'name',
      },
      {
        title: '操作',
        key: 'action',
      }
    ])

    onMounted(()=>{
      load()
    })
    const level = ref()
    const router = useRouter()
    const load = ()=>{
      axios.get("api/getDocByEbookId?id=" + router.currentRoute.value.query.id).then(res=>{
        if (res.data.code === "200"){
          doc.value = res.data.date
          level.value = arrayToTree(doc.value, 0)

          treeData.value = JSON.parse(JSON.stringify(level.value))
          treeData.value.unshift({id:0, name:"无"})
        } else {
          message.error(res.data.msg);
        }
      })
    }

    const loadContent = (id)=>{
      axios.get("api/findContent/" + id).then(res=>{
        if (res.data.code === "200"){
          valueHtml.value = res.data.date
        } else {
          message.error(res.data.msg);
        }
      })
    }

    const handleTableChange = ()=>{
      load()
    }

    const showDrawer = ()=>{
      visible.value = true
    }


    const treeData = ref();
    const setDisabled = (data, id) =>{
      for (let i=0; i<data.length; i++) {
        const d = data[i]
        if (d.id === id) {
          d.disabled = true
        // 遍历子文档
          const child = d.children
          if (!isEmpty(child)) {
            for (let j=0; j<child.length; j++) {
              setDisabled(child, child[j].id)
            }
          }
        } else {
          const child = d.children
          if (!isEmpty(child)) {
            setDisabled(child, id)
          }
        }
      }
    }

    const visible = ref(false);
    const confirmLoading = ref(false);

    const edit = (record) => {
      loadContent(record.id);
      formState.value = JSON.parse(JSON.stringify(record));

      treeData.value = JSON.parse(JSON.stringify(level.value))
      setDisabled(treeData.value, record.id)
      treeData.value.unshift({id:0, name:"无"})

      visible.value = false;
    };

    const add = () => {
      formState.value = {};
      // visible.value = true;
      load()
      valueHtml.value=''
    };

    const del = (id) => {
      axios.delete("api/deleteDoc/" + id).then(res=>{
        if (res.data.code === "200"){
          message.success(res.data.msg);
          load()
        } else {
          message.error(res.data.msg);
        }
      })
    };

    const handleOk = () => {
      formState.value.content = valueHtml.value
      console.log("content : "+formState.value.content)

      confirmLoading.value = true;
      formState.value.ebookId = router.currentRoute.value.query.id
      axios.post("api/saveDoc",formState.value).then(res=>{
        confirmLoading.value = false;
        // visible.value = false;
        if (res.data.code === "200"){
          load()
          message.success(res.data.msg);
        } else {
          message.error(res.data.msg);
        }
      })

    };

    return {
      doc,
      columns,
      handleTableChange,

      visible,
      showDrawer,
      confirmLoading,
      add,
      edit,
      del,
      handleOk,
      labelCol: { style: { width: '150px' } },
      wrapperCol: { span: 14 },
      formState,
      load,
      level,
      treeData,

      editorRef,
      valueHtml,
      mode: 'default', // 或 'simple'
      toolbarConfig,
      editorConfig,
      handleCreated,
    }
  }
}
</script>

<style>
/* table 样式 */
.wangEditor table {
  border-top: 1px solid #ccc;
  border-left: 1px solid #ccc;
}
.wangEditor table td,
.wangEditor table th {
  border-bottom: 1px solid #ccc;
  border-right: 1px solid #ccc;
  padding: 3px 5px;
}
.wangEditor table th {
  border-bottom: 2px solid #ccc;
  text-align: center;
}

/* blockquote 样式 */
.wangEditor blockquote {
  display: block;
  border-left: 8px solid #d0e5f2;
  padding: 5px 10px;
  margin: 10px 0;
  line-height: 1.4;
  font-size: 100%;
  background-color: #f1f1f1;
}

/* code 样式 */
.wangEditor code {
  display: inline-block;
  *display: inline;
  *zoom: 1;
  background-color: #f1f1f1;
  border-radius: 3px;
  padding: 3px 5px;
  margin: 0 3px;
}
.wangEditor pre code {
  display: block;
}

/* ul ol 样式 */
.wangEditor ul, ol {
  margin: 10px 0 10px 20px;
}

</style>